﻿using ConsoleApp;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace ConsoleApp_core
{
    /// <summary>
    /// 延迟类
    /// </summary>
    public class LazyClass
    {
        /// <summary>
        /// 普通延迟
        /// </summary>
        public void Show()
        {
            //不会去查数据，只是延迟指定数据如何查询
            var lazyInput = new LazyInput(
                new Lazy<Order[]>(() => { return AppDBData.GetDBOrders().ToArray(); }, true),
                new Lazy<Student[]>(() => { return AppDBData.GetDBStudents().ToArray(); }, true)
                );

            //真实获取数据：.Value
            //好处：用到什么数据，才去查什么数据。
            var isOrdersCreated = lazyInput._lazyOrders.IsValueCreated;//fasle
            var orders = lazyInput.GetOrders();
            var isOrdersCreated2 = lazyInput._lazyOrders.IsValueCreated;//true

            //好处2：数据初始化后，不会重新查询
            var students = lazyInput.GetStudents();
            var students2 = lazyInput.GetStudents();

        }

    }


    public class LazyInput
    {
        public readonly Lazy<Order[]> _lazyOrders;
        public readonly Lazy<Student[]> _lazyStudents;

        public LazyInput(Lazy<Order[]> lazyOrders, Lazy<Student[]> lazyStudents)
        {
            _lazyOrders = lazyOrders;
            _lazyStudents = lazyStudents;
        }

        public IEnumerable<Order> GetOrders()
        {
            return _lazyOrders.Value;
        }

        public IEnumerable<Student> GetStudents()
        {
            return _lazyStudents.Value;
        }

    }


}
